package com.ligong.gptai.adopter;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ligong.gptai.dto.ChatImage;
import com.ligong.gptai.dto.ChatMessage;
import com.ligong.gptai.dto.ChatMessageStream;
import com.ligong.gptai.service.AliAIService;

@Service
public class AliAiServiceAdopter implements IAIServiceAdopter {
    @Autowired
    private AliAIService aliAIService;

    public ChatMessage sendText(String model, String message) {
        try {
            Map messageMap = aliAIService.sendText(model, message);
            // 适配
            ChatMessage chatMessage = new ChatMessage();
            List<Map> choices = (List<Map>) messageMap.get("choices");

            Map choice = choices.get(0);
            Map messageChoice = (Map) choice.get("message");

            chatMessage.setMessage(messageChoice.get("content").toString());

            chatMessage.setRole("assistant");
            chatMessage.setId(messageMap.get("id").toString());
            return chatMessage;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void sendText(String model, String message, Boolean stream, Consumer<ChatMessageStream> onDelta) {
        aliAIService.sendText(model, message, stream, (str) -> {
            ChatMessageStream chatMessageStream = new ChatMessageStream();
            chatMessageStream.setDelta(str);
            chatMessageStream.setId(UUID.randomUUID().toString());
            onDelta.accept(chatMessageStream);
        });
    }

    public ChatImage createImage(String model, String prompt, Integer n, String size) {
        try {
            Map imageMap = aliAIService.createImage(model, prompt, n, size);
            Map output = (Map) imageMap.get("output");

            List<Map> choices = (List<Map>) output.get("choices");

            Map choice = choices.get(0);
            Map messageMap = (Map) choice.get("message");

            List<Map> contentMap = (List<Map>) messageMap.get("content");

            ChatImage chatImage = new ChatImage();
            chatImage.setId(UUID.randomUUID().toString());
            chatImage.setImage(contentMap.get(0).get("image").toString());

            return chatImage;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
